package com.shundr.auth.frame.db;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.shundr.auth.common.model.AreaInfo;
import com.shundr.auth.frame.util.LLogger;
import com.shundr.auth.user.model.AttributeInfo;
import com.shundr.auth.user.model.UserInfo;
import com.shundr.truck.model.TruckInfo;

/**
 * 
 * DBHelper 数据库管理类
 * 
 * @author larry 2015-4-10 下午2:47:02
 * @version 1.0.0
 * 
 */
public class DBHelper extends OrmLiteSqliteOpenHelper {

	public static final String DATABASE_NAME = "shundr";

	public static int DATABASE_VERSION = 2;

	public DBHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase database,
			ConnectionSource connectionSource) {
		try {
			TableUtils.createTable(connectionSource, UserInfo.class);
			TableUtils.createTableIfNotExists(connectionSource, AreaInfo.class);
			TableUtils
					.createTableIfNotExists(connectionSource, TruckInfo.class);
			TableUtils.createTableIfNotExists(connectionSource,
					AttributeInfo.class);
		} catch (SQLException e) {
			LLogger.e("Unable to create datbases : " + DATABASE_NAME + " \n "
					+ e);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase database,
			ConnectionSource connectionSource, int oldVer, int newVer) {
		try {
			TableUtils.dropTable(connectionSource, AreaInfo.class, true);
			TableUtils.dropTable(connectionSource, UserInfo.class, true);
			onCreate(database, connectionSource);
		} catch (SQLException e) {
			LLogger.e("Unable to upgrade database from version " + oldVer
					+ " to new " + newVer + " \n " + e);
		}

	}

}
